package com.asp.aspchain.tstaccount.service;

import com.alibaba.fastjson.JSON;
import com.asp.aspchain.core.dao.AppBaseMapper;
import com.asp.aspchain.core.dao.TocAccountMapper;
import com.asp.aspchain.core.ethereum.EthService;
import com.asp.aspchain.core.model.AppBaseModel;
import com.asp.aspchain.core.model.TocAccountModel;
import com.asp.aspchain.core.util.AjaxResult;
import com.asp.aspchain.tstaccount.constants.ErrorCode;
import com.asp.aspchain.tstaccount.request.CrtAccountReq;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

@Service
public class EoaCrtaccService {
	private final static Logger logger = Logger.getLogger(EoaCrtaccService.class);

	@Autowired
	private TocAccountMapper tocAccountMapper;
	@Autowired
	EthService ethService;
	@Autowired
	AppBaseMapper appBaseMapper;

	//账户类型：eoa账户
	private String formtype = "00";
	//token类型：eth
	private String tokentype = "TST";
	//状态：锁定
	private String status = "01";

	public AjaxResult eoaCrtaccount(String json) {
		CrtAccountReq accountReq = JSON.parseObject(json, CrtAccountReq.class);

		//如果密码可为空
		String accountid = null;
		try {
			accountid = ethService.newAccount(accountReq.getPassword());
			if (StringUtils.isBlank(accountid)) {
				return new AjaxResult(ErrorCode.CREATE_FAIL, "tst创建账户失败", "tst创建账户失败");
			}
		} catch (IOException e) {
			logger.info("tst创建账户时发生错误");
			e.printStackTrace();
			return new AjaxResult(ErrorCode.CREATE_FAIL, "tst创建账户失败", "tst创建账户失败");
		}
		//获取appid
		AppBaseModel appBaseModel = new AppBaseModel();
		appBaseModel.setAppmark(accountReq.getAppmark());
		appBaseModel = appBaseMapper.selectOne(appBaseModel);
		//入库
		TocAccountModel tocAccountModel = new TocAccountModel();
		tocAccountModel.setAccountid(accountid);
		tocAccountModel.setAppid(appBaseModel.getAppid());
		tocAccountModel.setCreatetime(new Date());
		tocAccountModel.setUpdatetime(tocAccountModel.getCreatetime());
		tocAccountModel.setFromtype(formtype);
		tocAccountModel.setTokentype(tokentype);
		tocAccountModel.setIdtype(accountReq.getIdtype());
		tocAccountModel.setIdentityId(accountReq.getIdentification());
		tocAccountModel.setPhone(accountReq.getPhonenum());
		tocAccountModel.setStatus(status);
		tocAccountModel.setPassword(accountReq.getPassword());
		tocAccountMapper.insert(tocAccountModel);

		return new AjaxResult(ErrorCode.SUCCESS, "tst创建账户成功", accountid, "tst创建账户成功");
	}

}
